package com.bit.cfdi.web.dao.impl;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bit.cfdi.web.dao.ImagenDAO;
import com.bit.cfdi.web.domain.DBConstants;
import com.bit.cfdi.web.domain.Imagen;
import com.bit.cfdi.web.domain.Persona;

@Service
public class ImagenDAOImpl extends HibernateDaoSupport implements ImagenDAO {

	@Autowired
	public void init(final SessionFactory sessionFactory) {
		setSessionFactory(sessionFactory);
	}
	
	@Transactional
	@Override
	public void save(final Imagen imagen) {
		getHibernateTemplate().save(imagen);
	}
	
	@SuppressWarnings("unchecked")
	@Transactional
	@Override
	public List<Imagen> getFromPersona(final Persona persona) 
			throws DataAccessException {
		List<Imagen> images = getHibernateTemplate().find("" +
				"FROM Imagen as imagen " +
				"WHERE imagen.persona = ? " +
				"AND imagen.status = ? ",
				persona, DBConstants.STATUS_ACTIVE);
		return images;
	}
	
	@SuppressWarnings("unchecked")
	@Transactional
	@Override
	public Imagen getDefaultImage(final Persona persona) 
			throws DataAccessException {
		getHibernateTemplate().setMaxResults(1);
		List<Imagen> images = getHibernateTemplate().find("" +
				"FROM Imagen as imagen " +
				"WHERE imagen.persona = ? " +
				"AND imagen.status = ? " +
				"ORDER BY imagen.fechaModificacion DESC ",
				persona, DBConstants.STATUS_ACTIVE);
		getHibernateTemplate().setMaxResults(0);
		return !images.isEmpty() ? images.get(0) : null;
	}

}
